package framework.base;

import java.util.List;
import java.util.Map;

import framework.exceptions.ExceptionHandler;
import framework.security.models.SecurityMenu;
import framework.utils.SecurityUtil;
import framework.utils.StringUtil;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.Scope.Flash;
import play.mvc.Scope.RenderArgs;

public class BaseController extends Controller {
    
    public final static int PAGE_SIZE=10;
    
    /**
     * url过滤器,除了登录URL其他的都需要管理员登录验证
     */
    @Before(unless={"Application.index","Application.logout","Application.login"})
    static void requireBkUser(){
            //调用远程登陆接口
            if(!SecurityUtil.isLogin()){
                redirect("Application.index");
            }
//            }else{
//                SecurityUtil.getSelectedMenu();
//                Map<SecurityMenu,List<SecurityMenu>> resources=SecurityUtil.getResources();
//                RenderArgs.current().put("resources",resources);
//            }
       
    }
    
    
    /**
     * 获得页面传递过来的页面页数
     * @return
     */
    public static int getPageSize(){
        String _pageSize = params.get(Constant.PAGE_SIZE_PARAM_NAME);
        int pageSize = StringUtil.isBlank(_pageSize)?PAGE_SIZE:Integer.parseInt(_pageSize);
        return pageSize;
    }
    /**
     * 获得页面传递过来的当前页
     * @return
     */
    public static int getPageNo(Integer pageNo){
        return pageNo==null?1:pageNo;
    }
    /**
     * 如果页面传递的Query对象不存在，重新初始化一个新的query对象
     */
    public static BaseQuery getQuery(BaseQuery query,Class clazz){
        BaseQuery baseQuery=query;
        if(null==query&&null!=clazz){
            try {
                baseQuery=(BaseQuery)clazz.newInstance();
            }catch(Exception e) {
                ExceptionHandler.throwRuntimeException(e,"根据Class初始化BaseQuery对象失败。");
            }
        }
        return  baseQuery;
    }

    /**
     * 保存用户操作日志并flush到页面
     * @param msg
     */
    public static boolean saveUserLogAndNotice(String msg,boolean isSuccess){
       if(isSuccess){
           Flash.current().success(msg);
       }else{
           Flash.current().error(msg);
       }
        return true;
    }
    
    
}
